package cn.exrick.xboot.common.activeMQ;


import cn.exrick.xboot.common.constant.CommonConstant;
import cn.exrick.xboot.common.utils.ConfigMapUtil;
import cn.exrick.xboot.modules.CheckConn.CheckConnThread;
import cn.exrick.xboot.modules.CheckConn.entity.CheckConn;
import cn.exrick.xboot.modules.backlogOrFullList.entity.BacklogOrFullList;
import cn.exrick.xboot.modules.backlogOrFullList.service.IbacklogOrFullListService;
import cn.exrick.xboot.modules.news.entity.news;
import cn.exrick.xboot.modules.news.service.InewsService;
import cn.exrick.xboot.modules.notice.service.INoticeService;
import cn.exrick.xboot.modules.subsystemNews.entity.SubsystemNews;
import cn.exrick.xboot.modules.subsystemNews.service.ISubsystemNewsService;
import cn.exrick.xboot.modules.system.entity.System;
import cn.exrick.xboot.modules.system.service.ISystemService;
import cn.exrick.xboot.modules.warning.entity.Warning;
import cn.exrick.xboot.modules.warning.service.IWarningService;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * xbw
 * 接收消息推送接口
 * 队列的消费者
 */
@Service
@Controller
public class CustomerRest {
    static Log log = LogFactory.get(CustomerRest.class);
    @Autowired
    ISubsystemNewsService iSubsystemNewsService;
    @Autowired
    private IbacklogOrFullListService ibacklogOrFullListService;
    @Autowired
    private InewsService inewsService;
    @Autowired
    private INoticeService iNoticeService;
    @Autowired
    private IWarningService iWarningService;
    @Autowired
    private  RedisTemplate redisTemplate;
    @Autowired
    private ISystemService iSystemService;
    @Autowired
    private CheckConnThread checkConnThread;

    /**
     * 将监听到的新闻，公告保存到数据库中，用户登录时从数据库中读取
     */
    @JmsListener(destination = "portalnews")
    public void getQueue(String info) throws Exception {
        log.info("监听新闻公告消息队列的信息:" + info);


        try {
            JSONObject jsonInfo = JSON.parseObject(info);
            JSONObject Data = JSON.parseObject(jsonInfo.getString("data"));//取出json数据中的data

            String infoId = Data.getString("newsID");
            String titlt = Data.getString("title");
            String department = Data.getString("department");
            String sender = Data.getString("sender");
            String msgtype = Data.getString("msgtype");
            String createtime = Data.getString("createtime");
            //add njp 20200428 业务状态（删除：delete）
            String changType = Data.getString("changingtype");
            Date   createdate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(createtime);

           if ("1".equals(msgtype)) {//'1'代表这条数据是新闻
               news newsInfo=new news();;
               List<news> newslist = inewsService.selectNewsByInfoId(infoId);
                   if(newslist.size()>0){
                       //newsInfo=newslist.get(0);
                       newsInfo.setId(newslist.get(0).getId());
                   }
                    if("delete".equals(changType)){
                   //执行删除操作
                   inewsService.removeById(newsInfo.getId());
                     }else {

                       /**
                        * modify  njp 20191104 begin
                        * 将单点地址修改成动态的配置在这里不做存储
                        */
                       //String headUrl = ConfigMapUtil.getValueByKey("SystemFinance.name");
                       //newsInfo.setUrl(headUrl);
                       /**
                        * modify  njp 20191104 end
                        * 将单点地址修改成动态的配置在这里不做存储
                        */
                       newsInfo.setInfoId(infoId);
                       newsInfo.setNewsTitle(titlt);
                       newsInfo.setDepartment(department);
                       /**
                        * 注意：在添加Source字段是一定要与字典表一一对应
                        */
                       newsInfo.setSource(sender);
                       newsInfo.setCreateTime(createdate);
                       newsInfo.setUpdateTime(new Date());
                       newsInfo.setInfoCode(CommonConstant.infoCode);  //来自异构系统的新闻
                       newsInfo.setNewsRate(10);//添加新闻的默认等级
                       newsInfo.setNewsRelease(1);//添加新闻默认发布状态
                       //inewsService.save(newsInfo);
                       //njp modify 20200428 添加修改逻辑
                       inewsService.saveOrUpdate(newsInfo);
                       log.info("测试是否转换成实体数据:" + newsInfo.getInfoId());
                     }

            } else {
               if("delete".equals(changType)){
                   //执行删除操作
                   //inewsService.removeById(newsInfo.getId());
                   Map<String,Object> map=new HashMap<>();
                   map.put("infoId",infoId);
                   iSubsystemNewsService.removeByMap(map);
               }else {
                   SubsystemNews NoticeInfo = new SubsystemNews();
                   //暂时规定为这个常量，日后对接其他系统再更改
                   //String headUrl = ConfigMapUtil.getValueByKey("SystemFinance.name");
                   //NoticeInfo.setUrl(headUrl);
                   NoticeInfo.setInfoId(infoId);
                   NoticeInfo.setTitle(titlt);
                   NoticeInfo.setDepartment(department);
                   NoticeInfo.setSource(sender);
                   NoticeInfo.setCreateTime(createdate);
                   NoticeInfo.setUpdateTime(new Date());
                   NoticeInfo.setInfoCode(CommonConstant.infoCode);  //来自异构系统的公文
                   iSubsystemNewsService.save(NoticeInfo);
                   log.info("测试是否转换成实体数据:" + NoticeInfo.getUrl());
               }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 将监听到的待办，已办保存到数据库中，用户登录时从数据库中读取
     */
    @JmsListener(destination = "change")
    public void getMessageQueue(String info) throws Exception {
        log.info("监听待办已办消息队列的信息:" + info);

        BacklogOrFullList backlogOrFullList = new BacklogOrFullList();
        try {
            JSONObject jsonInfo = JSON.parseObject(info);
            JSONObject Data = JSON.parseObject(jsonInfo.getString("data"));//取出json数据中的data

            String titlt = Data.getString("title");
            String messageID = Data.getString("messageID");
            String infoId = Data.getString("doID");
            String moduleName = Data.getString("sender");
            String userCode = Data.getString("usercode");
            String code = Data.getString("changingtype");
            String createtime = Data.getString("createtime");
            Date   createdate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(createtime);

            backlogOrFullList.setMessageId(messageID);
            backlogOrFullList.setTitle(titlt);
            backlogOrFullList.setInfoId(infoId);
            backlogOrFullList.setCode(code);
            backlogOrFullList.setModuleName(moduleName);
            backlogOrFullList.setUserCode(userCode);
            backlogOrFullList.setCreateTime(createdate);

           /* Map<Object, Object> mapId = new HashMap<>();
            mapId.put("userCode", userCode);
            mapId.put("messageID", messageID);
            String DBMessageID = ibacklogOrFullListService.selectInfoId(mapId);*/

           //njp TODO 在添加待办时判断messageID消息是否重复如果重复按照修改操作将本地的删除然后新增一条

           //njp modify 2020027 done代表待办变已办 begin
            if ("done".equals(code)) {
                //njp modify 2020027 done代表待办变已办 end
                Map<String, Object> map = new HashMap<>();
                map.put("user_code", userCode);
                map.put("message_id", messageID);
                //约定大于配置（约定待办已办的messageid是全局唯一的）
                map.put("code","todo");
                List<BacklogOrFullList> backlogOrFullLists=new ArrayList<>(ibacklogOrFullListService.listByMap(map));
                if(backlogOrFullLists.size()>0){
                    //做修改操作前提
                    backlogOrFullList.setId(backlogOrFullLists.get(0).getId());
                }
                //njp add 20200506 避免多次存储同一条待办数据，先判断该条数据是否存在 end

                //njp  modify 2020027 todo代表待办（新增待办）
                ibacklogOrFullListService.saveOrUpdate(backlogOrFullList);
                //njp 修改成saveorupdate Integer integer = ibacklogOrFullListService.UpdateMseeageType(map);
                //   njp add  待办变已办后向app推送待办数量（ios推送待办总数，安卓推送待办总数）
                Integer num = ibacklogOrFullListService.selectBacklogAngleNum(userCode);
                //向ios推送待办总数（待办变已办不在APP弹通知）
                ibacklogOrFullListService.sendBacklogAngleToAPPIos(userCode,num, CommonConstant.ALERT_OFF);
                //向安卓推送待办总数
                ibacklogOrFullListService.sendBacklogAngleAllToAPPAndroid(userCode,num);
            } else if("todo".equals(code)){
                //njp add 20200506 避免多次存储同一条待办数据，先判断该条数据是否存在 begin
                Map<String, Object> mapId = new HashMap<>();
                mapId.put("user_code", userCode);
                mapId.put("message_id", messageID);
                mapId.put("code","todo");
                //String DBMessageID = ibacklogOrFullListService.selectInfoId(mapId);

                List<BacklogOrFullList> backlogOrFullLists1 = ibacklogOrFullListService.listByMap(mapId);
                List<BacklogOrFullList> backlogOrFullLists=new ArrayList<>(backlogOrFullLists1);
                if(backlogOrFullLists.size()>0){
                    //做修改操作
                    backlogOrFullList.setId(backlogOrFullLists.get(0).getId());
                }
                //njp add 20200506 避免多次存储同一条待办数据，先判断该条数据是否存在 end

                //njp  modify 2020027 todo代表待办（新增待办）
                boolean b = ibacklogOrFullListService.saveOrUpdate(backlogOrFullList);
                log.info("转换成待办实体数据:" + backlogOrFullList.toString());
                //  njp add  新增待办后向 app推送待办数量（ios推送待办总数，安卓推送新增的数量）
                //1.先查询出该用户的待办数量（该方法在待办数量和已办数量发生变化时调用）
                Integer num = ibacklogOrFullListService.selectBacklogAngleNum(userCode);
                String alert= CommonConstant.BACKLOG_H+backlogOrFullList.getTitle()+ CommonConstant.BACKLOG_END;
                //向ios推送待办总数
                ibacklogOrFullListService.sendBacklogAngleToAPPIos(userCode,num,alert);
                //向安卓推送待办新增的数量（目前的逻辑是推送一条）
                ibacklogOrFullListService.sendBacklogAngleToAPPAndroid(userCode,1,alert);
            }else if ("delete".equals(code)){
                // njp modify 2020027   delete代表删除待办（删除待办待办）begin
                // 1.根据数据messageID和usercode删除portal中的待办（该删除操作是为了配合流程中的取回操作等）
                Map<String,Object> map=new HashMap<>();
                map.put("user_code",userCode);
                map.put("message_id",messageID);
                //njp addt 添加只删除待办数据的逻辑
                map.put("code","todo");
                //ibacklogOrFullListService.deleteBacklogByMessageID(messageID);
                ibacklogOrFullListService.removeByMap(map);
                //   njp add  删除待办后向app推送待办数量（ios推送待办总数，安卓推送待办总数）
                Integer num = ibacklogOrFullListService.selectBacklogAngleNum(userCode);
                //向ios推送待办总数(删除状态不在APP弹通知)
                ibacklogOrFullListService.sendBacklogAngleToAPPIos(userCode,num, CommonConstant.ALERT_OFF);
                //向安卓推送待办总数
                ibacklogOrFullListService.sendBacklogAngleAllToAPPAndroid(userCode,num);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @JmsListener(destination = "course")
    public void getCourseQueue(String info) throws Exception {
        log.info("监听在线教育课程的消息队列信息:" + info);

        BacklogOrFullList backlogOrFullList = new BacklogOrFullList();

        try {
            JSONObject jsonInfo = JSON.parseObject(info);
            JSONObject Data = JSON.parseObject(jsonInfo.getString("data"));//取出json数据中的data

            String infoId = Data.getString("messageID");
            String moduleName = Data.getString("sender");
            String userCode = Data.getString("usercode");
            String code = Data.getString("changingtype");
            String createtime = Data.getString("createtime");
            Date   createdate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(createtime);

            backlogOrFullList.setInfoId(infoId);
            backlogOrFullList.setCode(code);
            backlogOrFullList.setModuleName(moduleName);
            backlogOrFullList.setUserCode(userCode);
            backlogOrFullList.setCreateTime(createdate);

            Map<Object,Object> mapId = new HashMap<>();
            mapId.put("userCode", userCode);
            mapId.put("infoId", infoId);
            String DBInfo = ibacklogOrFullListService.selectInfoId(mapId);

            if (infoId.equals(DBInfo)) {
                Map<Object, Object> map = new HashMap<>();
                map.put("userCode", userCode);
                map.put("infoId", infoId);
                map.put("code", code);
                map.put("updateTime", createdate);

                ibacklogOrFullListService.UpdateMseeageType(map);
            } else {
                ibacklogOrFullListService.save(backlogOrFullList);
                log.info("测试是否转换成实体数据:" + backlogOrFullList.getCode());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @JmsListener(destination = "warningInfo")
    public void getWarningInfo(String info) throws Exception {
        log.info("监听预警信息的消息队列信息:" + info);
        Warning warning =  new Warning();

        try {
            JSONObject jsonInfo = JSON.parseObject(info);
            JSONObject Data = JSON.parseObject(jsonInfo.getString("data"));//取出json数据中的data
            String title = Data.getString("title");
            String moduleName = Data.getString("sender");
            String infoId = Data.getString("warningID");
            String userCode = Data.getString("usercode");
            String createtime = Data.getString("createtime");
            Date   createdate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(createtime);
            String url = ConfigMapUtil.getValueByKey("SystemFinance.name");

            warning.setUrl(url);
            warning.setInfoId(infoId);
            warning.setTitle(title);
            warning.setModuleName(moduleName);
            warning.setUserCode(userCode);
            warning.setCreateTime(createdate);

            iWarningService.save(warning);
            log.info("测试是否转换成实体数据:" + warning.getTitle());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }




    /**
     * 待办已办初始化消费者
     */
    @JmsListener(destination = "initBacklog")
    public void initBackLog(String info) throws Exception {
        log.info("监听待办已办消息队列‘initBacklog’的信息:" + info);

        try {
            JSONObject jsonInfo = JSON.parseObject(info);
            JSONArray arr = jsonInfo.getJSONArray("datas");
            //JSONObject Data = JSON.parseObject(jsonInfo.getString("data"));//取出json数据中的data
            //JSONArray jsonArray = jsonInfo.getJSONArray("data");
            log.info("接受数组长度"+arr.size());
            for (int i = 0; i < arr.size(); i++) {
               JSONObject Data = arr.getJSONObject(i);
               BacklogOrFullList backlogOrFullList = new BacklogOrFullList();
            String titlt = Data.getString("title");
            String messageID = Data.getString("messageID");
            String infoId = Data.getString("doID");
            String moduleName = Data.getString("sender");
            String userCode = Data.getString("usercode");
            String code = Data.getString("changingtype");
            String createtime = Data.getString("createtime");
            Date   createdate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(createtime);

            backlogOrFullList.setMessageId(messageID);
            backlogOrFullList.setTitle(titlt);
            backlogOrFullList.setInfoId(infoId);
            backlogOrFullList.setCode(code);
            backlogOrFullList.setModuleName(moduleName);
            backlogOrFullList.setUserCode(userCode);
            backlogOrFullList.setCreateTime(createdate);

           /* Map<Object, Object> mapId = new HashMap<>();
            mapId.put("userCode", userCode);
            mapId.put("messageID", messageID);
            String DBMessageID = ibacklogOrFullListService.selectInfoId(mapId);*/

            //njp TODO 在添加待办时判断messageID消息是否重复如果重复按照修改操作将本地的删除然后新增一条

            //njp modify 2020027 done代表待办变已办 begin
            if ("done".equals(code)) {
                //njp modify 2020027 done代表待办变已办 end
                Map<String, Object> map = new HashMap<>();
                map.put("user_code", userCode);
                map.put("message_id", messageID);
                //约定大于配置（约定待办已办的messageid是全局唯一的）
                map.put("code","todo");
                List<BacklogOrFullList> backlogOrFullLists=new ArrayList<>(ibacklogOrFullListService.listByMap(map));
                if(backlogOrFullLists.size()>0){
                    //做修改操作前提
                    backlogOrFullList.setId(backlogOrFullLists.get(0).getId());
                }
                //njp add 20200506 避免多次存储同一条待办数据，先判断该条数据是否存在 end
                //njp  modify 2020027 todo代表待办（新增待办）
                backlogOrFullList.setUpdateTime(createdate);
                ibacklogOrFullListService.saveOrUpdate(backlogOrFullList);

            } else if("todo".equals(code)){
                //njp add 20200506 避免多次存储同一条待办数据，先判断该条数据是否存在 begin
                Map<String, Object> mapId = new HashMap<>();
                mapId.put("user_code", userCode);
                mapId.put("message_id", messageID);
                mapId.put("code","todo");
                //String DBMessageID = ibacklogOrFullListService.selectInfoId(mapId);
                //todo
                List<BacklogOrFullList> backlogOrFullLists=new ArrayList<>(ibacklogOrFullListService.listByMap(mapId));
                if(backlogOrFullLists.size()>0){
                    //做修改操作
                    backlogOrFullList.setId(backlogOrFullLists.get(0).getId());
                }
                //njp add 20200506 避免多次存储同一条待办数据，先判断该条数据是否存在 end
                //njp  modify 2020027 todo代表待办（新增待办）
                ibacklogOrFullListService.saveOrUpdate(backlogOrFullList);
                log.info("转换成待办实体数据:" + backlogOrFullList.toString());
                //  njp add  新增待办后向 app推送待办数量（ios推送待办总数，安卓推送新增的数量）
            }else if ("delete".equals(code)){
                // njp modify 2020027   delete代表删除待办（删除待办待办）begin
                // 1.根据数据messageID和usercode删除portal中的待办（该删除操作是为了配合流程中的取回操作等）
                Map<String,Object> map=new HashMap<>();
                map.put("user_code",userCode);
                map.put("message_id",messageID);
                //njp addt 添加只删除待办数据的逻辑
                map.put("code","todo");
                //ibacklogOrFullListService.deleteBacklogByMessageID(messageID);
                ibacklogOrFullListService.removeByMap(map);
            }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    /**
     * 检测三方系统连接状态逻辑的消者
     */
    @JmsListener(destination = "checkConn")
    public void checkConn(String info) throws Exception {
        log.info("检测三方系统连接状态消息队列‘checkConn’的信息:" + info);

        try {
          JSONObject jsonInfo = JSON.parseObject(info);
          JSONObject Data = JSON.parseObject(jsonInfo.getString("data"));//取出json数据中的data
            //推送周期也就是60s后再次推送
            String period = Data.getString("period");
            Integer periodTime = Integer.valueOf(period);
            //预留业务类型字段
            String type = Data.getString("type");
            //对应系统标识
            String sender = Data.getString("sender");
            RedisSerializer stringSerializer = new StringRedisSerializer();
            redisTemplate.setKeySerializer(stringSerializer);
            redisTemplate.setValueSerializer(stringSerializer);
            redisTemplate.opsForValue().set(CommonConstant.checkConn + sender, sender, periodTime, TimeUnit.SECONDS);
            CheckConn checkConn = new CheckConn(periodTime, type, sender);
            System system = new System();
            //将状态设置为正常
            system.setConnStatus("1");
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("module_name",checkConn.getSender());
            boolean update = iSystemService.update(system, queryWrapper);
            log.info(update?"修改服务状态成功":"修改服务状态失败");
            //延时执行校验连接
            checkConnThread.timeOut(checkConn);

        } catch (Exception e) {
            log.error("三方系统连接状态监测出错");

        }
    }


    @JmsListener(destination = "topicTest")
    public void topicTest(String info) throws Exception {
        log.info("topicTest:"+info);
    }

}

